//导入
const express = require("express");
const fs = require('fs');
const moment = require('moment');

//创建应用对象
const app = express();

function getClientIP(req) {
  return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
      req.connection.remoteAddress || // 判断 connection 的远程 IP
      req.socket.remoteAddress || // 判断后端的 socket 的 IP
      req.connection.socket.remoteAddress;
};

//中间件  本质就是函数
let recordMiddleware = (req, res, next) => {
  //获取当前的时间
  let timeStr = moment().format('YYYY-MM-DD HH:mm:ss');
  //获取当前请求的 URL
  let url = decodeURI(req.url);
  //获取 ip
  let ip = getClientIP(req);
  //拼接字符串
  let str = `[${timeStr}] ${url} ${ip}\r\n`;
  fs.writeFileSync('./access.log', str, {flag: 'a'});
  //调用后续的路由回调
  next();
};
//使用中间件
app.use(recordMiddleware);


//创建 home 的路由规则
app.get('/home', (req, res) => {
  res.sendFile(__dirname + '/html/home.html');
});

app.get('/admin', (req, res) => {
  res.send('<h1>后台首页</h1>');
});

app.get('/cart', (req, res) => {
  res.send('<h1>购物车</h1>');
});

//启动服务
app.listen(8080, () => {
  console.log("启动成功....");
});
